package com.ucode.hrm.service;

import cn.hutool.core.collection.CollUtil;
import com.ucode.model.hrm.HrmAttendanceRecord;
import com.ucode.model.hrm.enums.HrmAttendanceRecordsStatusEnum;
import com.ucode.model.hrm.vo.HrmAttendanceMonthlyStatsVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HrmAttendanceStatisticsService {

    @Resource
    private HrmAttendanceRecordService hrmAttendanceRecordService;

    /**
     * 统计员工在指定月份的考勤数据
     * 
     * @param employeeId 员工
     * @param month 要统计的月份（格式：yyyy-MM）
     * @return 考勤统计结果
     */
    public HrmAttendanceMonthlyStatsVO getMonthlyStats(Long employeeId, String month) {
        YearMonth targetMonth = YearMonth.parse(month);
        LocalDate startDate = targetMonth.atDay(1);
        LocalDate endDate = targetMonth.atEndOfMonth();

        Map<String, Object> condition = new HashMap<>();
        condition.put("workStartDate",startDate);
        condition.put("workEndDate",endDate);
        condition.put("employeeId",employeeId);
        condition.put("deltag",false);

        List<HrmAttendanceRecord> records = hrmAttendanceRecordService.queryObjectForList(condition,0);
        // 过滤出指定月份的记录
        //List<HrmAttendanceRecord> monthlyRecords = records.stream()
        //        .filter(record -> !record.getWorkDate().isBefore(startDate) &&
        //                          !record.getWorkDate().isAfter(endDate))
        //        .collect(Collectors.toList());
        
        HrmAttendanceMonthlyStatsVO stats = new HrmAttendanceMonthlyStatsVO();
        stats.setMonth(month);

        boolean isData = CollUtil.isNotEmpty( records);
        // 计算各项指标
        stats.setAttendanceDays(isData ? calculateAttendanceDays(records) :0);
        stats.setLateMinutes(isData ? calculateLateMinutes(records) : 0);
        stats.setEarlyLeaveCount(isData ? calculateEarlyLeaveCount(records) : 0);
        stats.setMissingPunchCount(isData ? calculateMissingPunchCount(records) : 0);
        stats.setFieldWorkCount(isData ? calculateFieldWorkCount(records) : 0);
        
        // 以下两项需要其他数据源支持
        stats.setReissueCount(0); // 需要补卡记录数据
        stats.setLeaveCount(0);   // 需要请假记录数据
        
        return stats;
    }
    
    /**
     * 计算出勤天数
     * 只要当天有打卡记录（上班或下班）就算出勤
     */
    private int calculateAttendanceDays(List<HrmAttendanceRecord> records) {
        return (int) records.stream()
                .filter(record -> record.getClockInTime() != null || record.getClockOutTime() != null)
                .count();
    }
    
    /**
     * 计算迟到总分钟数
     */
    private int calculateLateMinutes(List<HrmAttendanceRecord> records) {
        return records.stream()
                .filter(record -> record.getLateDuration() != null && record.getLateDuration() > 0)
                .mapToInt(HrmAttendanceRecord::getLateDuration)
                .sum();
    }
    
    /**
     * 计算早退次数
     */
    private int calculateEarlyLeaveCount(List<HrmAttendanceRecord> records) {
        return (int) records.stream()
                .filter(record -> record.getEarlyLeaveDuration() != null && record.getEarlyLeaveDuration() > 0)
                .count();
    }
    
    /**
     * 计算缺卡次数
     * 包括：全天缺卡、只缺上班卡、只缺下班卡
     */
    private int calculateMissingPunchCount(List<HrmAttendanceRecord> records) {
        return (int) records.stream()
                .filter(record -> {
                    boolean missingClockIn = record.getClockInTime() == null;
                    boolean missingClockOut = record.getClockOutTime() == null;
                    
                    // 全天缺卡
                    if (missingClockIn && missingClockOut) {
                        return true;
                    }
                    
                    // 检查状态是否为缺卡状态
                    Integer status = record.getStatuz();
                    return status != null && (
                        status == HrmAttendanceRecordsStatusEnum.IN_ABSENT.getCode()||
                        status == HrmAttendanceRecordsStatusEnum.OUT_ABSENT.getCode() ||
                        status == HrmAttendanceRecordsStatusEnum.ABSENT.getCode()
                    );
                })
                .count();
    }
    
    /**
     * 计算外勤次数
     * 上班或下班任意一次在范围外打卡就算外勤
     */
    private int calculateFieldWorkCount(List<HrmAttendanceRecord> records) {
        return (int) records.stream()
                .filter(record -> {
                    Boolean inRangeClockIn = record.getClockInInRange();
                    Boolean inRangeClockOut = record.getClockOutInRange();
                    
                    // 上班打卡在范围外
                    boolean fieldWorkIn = inRangeClockIn != null && !inRangeClockIn;
                    // 下班打卡在范围外
                    boolean fieldWorkOut = inRangeClockOut != null && !inRangeClockOut;
                    
                    return fieldWorkIn || fieldWorkOut;
                })
                .count();
    }

}